package operation;

import User.User;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ReceiveMessage implements IOperation {

    public static final int TIME_OUT = 15_000; //接收请求等待时间

    @Override
    public boolean operate(User user) {
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        InputStream inputStream = null;

        try {
            int count = 0; //弹幕数
            //配置服务器端端口用于接收请求
            serverSocket = new ServerSocket(9090);
            System.out.println("当前主机IP：" + InetAddress.getLocalHost());
            while (true) {
                if (count == 5) {
                    System.out.println("弹幕接收已达上限，接收端自动关闭。");
                    return true;
                }
                serverSocket.setSoTimeout(TIME_OUT); //设置等待时间
                clientSocket = serverSocket.accept(); //监听请求
                inputStream = clientSocket.getInputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    System.out.println(clientSocket.getInetAddress() + "发来信息：");
                    System.out.println(new String(buffer, 0, len));
                }
                count++; //弹幕+1
            }
        } catch (IOException e) {
            System.out.println(e.getMessage() + "，超过" + (TIME_OUT / 1000) +
                    "秒未接收到信息，服务器端连接已关闭。");
        } finally {
            //关闭连接资源
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (clientSocket != null) {
                    clientSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}